#pragma once

#include <iostream>
#include <cstring>
#include <string>
#include <memory>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Log.hpp"
#include "InetAddr.hpp"


// 套接字封装 
namespace socket_ns
{
    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;

    using namespace log_ns;
    const static int default_backlog = 8;
    const static int default_sockfd = -1;

    enum
    {
        SOCKET_ERROR = 1, 
        BIND_ERROR, 
        LISTEN_ERROR
    };


    // 模板方法模式 
    // 基类含有一套固有的特定模板，把特定的方法做组合形成一套算法 
    class Socket
    {
    private:
    public:
        virtual void CreateSocketOrDie() = 0;
        virtual void BindOrDie(in_port_t port) = 0;
        virtual void ListenOrDie(int backlog = default_backlog) = 0;
        virtual int Accepter(InetAddr* cli_addr) = 0;
        virtual bool Connector(std::string& peerIP, in_port_t peerPort) = 0;
        virtual int GetSockfd() = 0;
        virtual void CloseSockfd() = 0;

        virtual ssize_t Recv(std::string* out) = 0;
        virtual ssize_t Send(const std::string& in) = 0;

        virtual void ReUseAddr() = 0;

    public:
        void BuildListenSocket(in_port_t port)
        {
            CreateSocketOrDie();
            ReUseAddr();
            BindOrDie(port);
            ListenOrDie();
        }

        bool BuildClientSocket(std::string& peerIP, in_port_t peerPort)
        {
            CreateSocketOrDie();
            return Connector(peerIP, peerPort);
        }

    private:
    };


    class TcpSocket : public Socket
    {
    private:
    public:
        TcpSocket(int sockfd = default_sockfd)
            : _sockfd(sockfd)
        {}

        void CreateSocketOrDie() override 
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket() -> Error, errno: %d -> %s\n", errno, strerror(errno));
                exit(SOCKET_ERROR);
            }
            LOG(INFO, "Create socket success, sockfd: %d\n", _sockfd);
        }

        void BindOrDie(in_port_t port) override 
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof local);
            local.sin_family = AF_INET;
            local.sin_port = ::htons(port);
            local.sin_addr.s_addr = INADDR_ANY;

            if ((::bind(_sockfd, (struct sockaddr*)&local, sizeof local)) < 0)
            {
                LOG(FATAL, "bind() -> Error, errno: %d -> %s\n", errno, strerror(errno));
                exit(BIND_ERROR);
            }
            LOG(INFO, "Bind success\n");
        }

        void ListenOrDie(int backlog) override 
        {
            if ((::listen(_sockfd, backlog)) < 0)
            {
                LOG(FATAL, "listen() -> Error, errno: %d -> %s\n", errno, strerror(errno));
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "Listen success\n");
        }

        int Accepter(InetAddr* cli_addr) override 
        {
            struct sockaddr_in client;
            socklen_t len = sizeof client;

            int sockfd = accept(_sockfd, (struct sockaddr*)&client, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "accept() -> Error, errno: %d -> %s\n", errno, strerror(errno));
                // return nullptr;
                return -1;
            }

            *cli_addr = InetAddr(client);
            // LOG(INFO, "Get a new link, client info: [%s], sockfd: %d\n", cli_addr->GetAddrStr().c_str(), sockfd);

            // return std::make_shared<TcpSocket>(sockfd);  // C++ 14
            return sockfd;
        }

        bool Connector(std::string& peerIP, in_port_t peerPort) override 
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof server);
            server.sin_family = AF_INET;
            server.sin_port = ::htons(peerPort);
            ::inet_pton(AF_INET, peerIP.c_str(), &server.sin_addr);

            int n = ::connect(_sockfd, (struct sockaddr*)&server, sizeof server);
            if (n < 0)
            {
                // LOG(ERROR, "connect() -> Error, errno: %d -> %s\n", errno, strerror(errno));
                return false;
            }
            return true;
        }

        ssize_t Recv(std::string* out) override
        {
            *out = "";
            char inBuffer[4096];
            ssize_t n = ::recv(_sockfd, inBuffer, (sizeof inBuffer) - 1, 0);
            if (n > 0)
            {
                inBuffer[n] = 0;
                *out += inBuffer;
            }
            return n;
        }

        ssize_t Send(const std::string& in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }

        void ReUseAddr() override
        {
            int opt = 1;
            ::setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
        }

        int GetSockfd() override
        {
            return _sockfd;
        }

        void CloseSockfd() override
        {
            if (_sockfd >= 0)
            {
                ::close(_sockfd);
                _sockfd = default_sockfd;
            }
        }

        ~TcpSocket()
        {
            CloseSockfd();
        }

    private:
        int _sockfd;  // 可以是 _listen_sockfd，也可以是普通的 IO 套接字
    };


    class UdpSocket : public Socket
    {
    private:
    public:
    private:
    };

} // namespace socket_ns



